// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const voiceCollection = db.collection('voice')
const cmtCollection = db.collection('comment')
const _ = db.command
let authorId = ''
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const id = event.id || ''
  const content = event.content || ''
  const state = event.state
  let breakOut
  if (id == '') return
  if (content == '') return

  if (state == 'comment'){
    
    await voiceCollection.doc(id).get().then(res => {
      authorId = res.data._openid
    })

    await cmtCollection.where({
      commentatorId: wxContext.OPENID,
      voiceId: id,
    }).get().then(res => {
      breakOut = res.data.length
    })

    if (breakOut != 0) return

    await cmtCollection.add({
      data: {
        commentatorId: wxContext.OPENID,
        voiceId: id,
        authorId,
        comment: content,
        commentDate: new Date().getTime(),
        reply: '',
        replyDate: ''
      }
    })
    
    await voiceCollection.doc(id).update({
      data: {
        commentCount: _.inc(1)
      }
    })

  }else{
    await cmtCollection.doc(id).update({
      data: {
        reply: content,
        replyDate: new Date().getTime()
      }
    })
  }
    

  return {
    event,
    openid: wxContext.OPENID
  }
}